package com.winit.common.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by wangjian on 16/1/16.
 */
public class Md5Util {
    private static Logger logger = LoggerFactory.getLogger(Md5Util.class);

    /**
     * @param str
     * @Description: 32位小写MD5
     */
    public static String parseStrToMd5L32(String str) {
        String reStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bytes) {
                int bt = b & 0xff;
                if (bt < 16) {
                    stringBuffer.append(0);
                }
                stringBuffer.append(Integer.toHexString(bt));
            }
            reStr = stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return reStr;
    }

    /**
     * 获取文件的md5值
     * @param path
     * @return
     */
    public static String getFileMd5(String path) {
        String md5 = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
        } catch (Exception e) {
            logger.error("com.winit.common.util.Md5Util.getFileMd5 异常 ." + path, e);
        } finally {
            if (fis != null) {
                IOUtils.closeQuietly(fis);
            }
        }
        return md5;
    }

    public static void main(String[] args) {
//        String passWord = args[0];
//        System.out.println(passWord);
//        System.out.println(Md5Util.parseStrToMd5L32(passWord));
//        System.out.println(Md5Util.getFileMd5("/usr/local/Beetle/sql/2017-12/mms/status.sq11111"));
        StringBuffer buffer = new StringBuffer();
        System.out.println(StringUtils.isEmpty(buffer.toString()));
    }

}
